<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="10">
        <el-col :span="11">
          <el-input placeholder="请输入要查询的Name" v-model="queryInfo.query" clearable
            @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index">
        </el-table-column>
        <el-table-column prop="username" label="姓名">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- scope.row 可以获取到当前列的数据 -->
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 依次是 修改，删除，分配按钮 -->
            <el-tooltip content="修改用户" placement="top" :enterable="false">
              <el-button size="mini" type="primary" icon="el-icon-edit"
                @click="showEditDialog(scope.row.id)">
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除用户" placement="top" :enterable="false">
              <el-button size="mini" type="danger" icon="el-icon-delete"
                @click="removeUserById(scope.row.id)">
              </el-button>
            </el-tooltip>
            <el-tooltip content="分配权限" placement="top" :enterable="false">
              <el-button size="mini" type="warning" icon="el-icon-setting"
                @click="allotUserRoles(scope.row)">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @closed="addDialogClosed">
      <!-- 内容主体区域  ref="addFormRef"干啥用的？-->
      <!-- 用来通过 this.$refs.addFormRes 来引用，执行该form对象的方法，例如重置方法-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px"
        status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%"
      @closed="editDialogClosed">
      <!-- 内容主体区域  ref="addFormRef"干啥用的？-->
      <!-- 用来通过 this.$refs.addFormRes 来引用，执行该form对象的方法，例如重置方法-->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px"
        status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="allotRightdialogVisible" width="50%"
      @close="setRoleDialogClosed">
      <!-- {{userInfo}} -->
      <p>当前用户：{{userInfo.username}}</p>
      <p>当前权限：{{userInfo.role_name}}</p>
      <p>分配权限：<el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </p>

      <span slot="footer" class="dialog-footer">
        <el-button @click="allotRightdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUserRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { log } from 'util'
export default {
  data() {
    // 表单自定义验证规则，验证邮箱
    const checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }

    // 表单自定义验证规则 验证手机号
    const checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb('请输入合法的手机号')
    }

    return {
      queryInfo: {
        query: '',
        // 当前的页码
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      currentPage4: 1,
      dialogVisible: false,
      editDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {},
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },

      // 分配角色对话框显示与否
      allotRightdialogVisible: false,
      // 当前要操作的用户信息，分配权限用
      userInfo: {},
      // 角色列表
      rolesList: [],
      // 已选角色id
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取所有用户信息
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })

      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }

      this.userList = res.data.users
      this.total = res.data.total
    },
    // 分页大小
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 页码变化
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },

    // 监听switch 用户状态改变
    async userStateChanged(userinfo) {
      // console.log(userinfo)
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )

      if (res.meta.status !== 200) {
        return this.$$message.error('修改用户状态失败')
      }

      this.$message.success('更新用户状态成功')
    },

    // 显示编辑对话框
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`users/${id}`)

      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }

      this.editForm = res.data
    },
    // 关闭对话框，清空暂留数据
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      // validate 方法是 element 自带的用于验证当前表单是否通过验证，
      // 当返回 false 时编写代码不允许提交数据
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.post('users', this.addForm)

        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }

        this.$message.success('添加成功')
        this.dialogVisible = false

        this.getUserList()
      })
    },
    // 编辑用户
    editUser() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          this.editForm
        )

        if (res.meta.status !== 200) {
          return this.$message.error('更新失败')
        }

        // 修改成功，三个操作
        // 提示修改成功，关闭对话框，更新数据列表
        this.$message.success('更新成功')
        this.editDialogVisible = false

        this.getUserList()
      })
    },
    // 根据 id 删除用户
    removeUserById(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('users/' + id)

          if (res.meta.status !== 200) {
            return this.$message.error('删除失败')
          }

          this.$message.success('删除成功')

          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 分配角色
    async allotUserRoles(userInfo) {
      this.userInfo = userInfo

      // 获取所有的角色列表，给选择项
      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }

      this.rolesList = res.data

      this.allotRightdialogVisible = true
    },

    // 保存用户角色修改
    async saveUserRole() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的权限')
      }

      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('修改用户角色失败')
      }

      this.$message.success('修改用户角色成功')
      this.getUserList()

      this.allotRightdialogVisible = false
    },

    // 设置 设置权限 对话框 关闭时 清空选择项
    setRoleDialogClosed() {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
</style>